
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Diagnostics;
using Util;

namespace API.Controllers
{
    public class ConfigurationController : BaseController
    {
        Repository<tConfiguration> _Configuration;
        Repository<tFace> _tFace;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public ConfigurationController(Repository<tConfiguration> Configuration, IMapper mapper, ISqlSugarClient db, Repository<tFace> tFace)
        {
            _Configuration = Configuration;
            _mapper = mapper;
            _db = db;
            _tFace = tFace;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveConfigurationInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tConfiguration>(dto);
                InitEntity(model);
                await _Configuration.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<ConfigurationOutput>>> GetList([FromBody] ConfigurationListInput dto)
        {
            ResultMsg<List<ConfigurationOutput>> result = new ResultMsg<List<ConfigurationOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tConfiguration>();
                //if (!string.IsNullOrWhiteSpace(dto.Name))
                //{
                //    exp.And(x => x.FName.Contains(dto.Name));
                //}
                var list = (await _Configuration.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var ConfigurationOutputs = _mapper.Map<List<ConfigurationOutput>>(list);
                return result.Success(ConfigurationOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<ConfigurationOutput>> GetTheOne(string id)
        {
            ResultMsg<ConfigurationOutput> result = new ResultMsg<ConfigurationOutput>();
            try
            {
                var model = await _Configuration.GetByIdAsync(id);
                var dao = _mapper.Map<ConfigurationOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _Configuration.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ResultMsg<ConfigurationDao>> GetConfiguration()
        {
            ResultMsg<ConfigurationDao> result = new ResultMsg<ConfigurationDao>();
            try
            {
                var list = _db.Queryable<tConfiguration>().ToList();

                ConfigurationDao dao = new ConfigurationDao();

                if (list!=null && list.Count > 0)
                {
                    dao.Lunch = list.Where(x => x.FCode == "Lunch").First().FCodeValue;
                    dao.Dinner = list.Where(x => x.FCode == "Dinner").First().FCodeValue;
                    dao.LunchStartScan = list.Where(x => x.FCode == "LunchStartScan").First().FCodeValue;
                    dao.LunchEndScan = list.Where(x => x.FCode == "LunchEndScan").First().FCodeValue;
                    dao.DinnerStartScan = list.Where(x => x.FCode == "DinnerStartScan").First().FCodeValue;
                    dao.DinnerEndScan = list.Where(x => x.FCode == "DinnerEndScan").First().FCodeValue;
                    dao.DinnerCost = list.Where(x => x.FCode == "DinnerCost").First().FCodeValue;
                    dao.voluntarily = list.Where(x => x.FCode == "voluntarily").First().FCodeValue;

                    var val = list.Where(x => x.FCode == "TravelTime").First().FCodeValue;
                    if (!string.IsNullOrEmpty(val))
                    {
                        JObject jo = JObject.Parse(val);
                        dao.TravelTime = Convert.ToBoolean(jo["TravelTime"]);
                        Util.valid_cycle cycle = new Util.valid_cycle();
                        JArray ja = JArray.Parse(jo["cycles"].ToString());
                        foreach (var token in ja)
                        {
                            cycle = new Util.valid_cycle();
                            cycle.start_time = token["start_time"].ToString();
                            cycle.end_time = token["end_time"].ToString();
                            dao.cycles.Add(cycle);
                        }
                    }
                }
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--GetConfiguration:" + ex.ToString());
                return result.Exception();
            }
        }

        /// <summary>
        /// 修改通行时间配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> UpdateConfigTravelTime(UpdateConfigTravelTimeInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {

                var model = _Configuration.GetFirst(x => x.FCode == "TravelTime");
                if (model == null)
                {
                    return result.Error("找不到相关的配置!");
                }

                model.FCodeValue = JsonConvert.SerializeObject(input);
                //配置了通行时间,把个人配置的通行时间清空
                if (input.TravelTime)
                {
                    var list = _tFace.GetList(c => !c.FDeleted);
                    list.ForEach(item =>
                    {
                        item.FValidCycle = JsonConvert.SerializeObject(input.cycles);
                    });
                    _tFace.UpdateRange(list);
                }


                _Configuration.Update(model);
                return result.Success("保存成功!");
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ConfigurationController--UpdateConfigTravelTime:" + ex.ToString());
                return result.Exception();
            }
        }
    }
}
